package yang.yu.sunny.domain;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.dayatang.domain.AbstractEntity;

import javax.persistence.*;
import java.util.*;

/**
 * 订单
 * Created by yyang on 16/3/15.
 */
@Entity
@Table(name = "orders")
public class Order extends AbstractEntity {

    @ManyToOne
    private Customer customer;

    @Temporal(TemporalType.TIMESTAMP)
    private Date created;

    private double totalPrice;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
    private Set<OrderItem> items = new HashSet<>();

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public Set<OrderItem> getItems() {
        return Collections.unmodifiableSet(items);
    }

    public void setItems(Set<OrderItem> items) {
        if (items == null) {
            totalPrice = 0;
            this.items = new HashSet<>();
            return;
        }
        this.items = Collections.unmodifiableSet(items);
        this.items.stream().forEach(orderItem -> {
            orderItem.setOrder(this);
            //orderItem.save();
        });
        totalPrice = this.items.stream().mapToDouble(OrderItem::getTotalPrice).sum();
    }

    public static Order get(Long id) {
        return getRepository().get(Order.class, id);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (!(o instanceof Order)) return false;

        Order order = (Order) o;

        return new EqualsBuilder()
                .appendSuper(super.equals(o))
                .append(this.getId(), order.getId())
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(getId())
                .toHashCode();
    }
}
